package tools

import (
	"encoding/json"
	"io/ioutil"
)

const (
	//dir = "./conf/"
	filename = "./conf/config.json"
)

func init() {
	Conf = make(map[string]string)

	//fmt.Println("filename:", filename)
	f, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(filename + err.Error())
	}
	m := make(map[string]string)
	if err := json.Unmarshal(f, &m); err != nil {
		panic(filename + err.Error())
	}

	for key, value := range m {
		Conf.Set(key, value)
	}

	//infos, err := ioutil.ReadDir(dir)
	//if err != nil {
	//	panic(err)
	//}
	//for _, v := range infos {
	//	vLen := len(v.Name())
	//	if !v.IsDir() && vLen >= 5 && v.Name()[vLen-5:vLen] == ".json" {
	//		f, err := ioutil.ReadFile(dir + v.Name())
	//		if err != nil {
	//			panic(dir + v.Name() + err.Error())
	//		}
	//		m := make(map[string]string)
	//		if err := json.Unmarshal(f, &m); err != nil {
	//			panic(dir + v.Name() + err.Error())
	//		}
	//
	//		for key, value := range m {
	//			Conf.Set(key, value)
	//		}
	//	}
	//}

	//fmt.Printf("[ config.json ] %#v\n", Conf)
}

type Config map[string]string

var Conf Config

func (c Config) Set(key, value string) {
	c[key] = value
}

func (c Config) Get(key string) (value string) {
	return c[key]
}

func (c Config) Save() error {
	bytes, err := json.Marshal(Conf)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(filename, bytes, 0); err != nil {
		return err
	}
	return nil
}
